import React, {useEffect, useState} from "react";
import type {IncomeLogItem} from "./data";
import {Avatar, message} from "antd";
import {deleteIncomeLog, queryIncomeLog, updateIncomeLog} from "./service";
import dayjs from "dayjs";
import UpdateForm from "./components/UpdateForm";
import Style from './style.less'
import {Dialog, DotLoading, InfiniteScroll, List, SwipeAction, Toast} from "antd-mobile";

/**
 * 删除节点
 *
 * @param record
 */
const handleSingleRemove = async (record: any) => {
  const hide = message.loading('正在删除');
  try {
    const res = await deleteIncomeLog({
      key: record.id,
    });
    hide();
    if (res) {
      if (res.status === 'done') {
        Toast.show({
          content: res.message,
          icon: "success"
        })
        return true;
      } else {
        Toast.show({
          content: res.message,
          icon: "fail"
        })
        return false;
      }
    } else {
      Toast.show({
        content: '请求超时，请稍后重试',
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    Toast.show({
      content: '删除失败，请重试',
      icon: "fail"
    })
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 * @param currentRow
 */

const handleUpdate = async (fields: any, currentRow?: IncomeLogItem) => {
  const hide = message.loading('正在修改');

  try {
    const res = await updateIncomeLog({
      id: currentRow?.id,
      ...fields,
    });
    if(res && res.status === "done" ){
      hide();
      Toast.show({
        content: res.message,
        icon: "success"
      })
      return true;
    }else {
      hide()
      Toast.show({
        content: res.message,
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    Toast.show({
      content: '更新失败，请重试！',
      icon: "fail"
    })
    return false;
  }
};

export type Props = {
  update: boolean;
};

const IncomeLogs: React.FC<Props> = (props: {update: boolean}) => {

  /** 更新窗口的弹窗 */
  const [currentRow, setCurrentRow] = useState<IncomeLogItem>();
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  // 获取流水数据
  const [page, setPage] = useState(1)
  const [data, setData] = useState<IncomeLogItem[]>(new Array())
  const [hasMore, setHasMore] = useState(true)

  async function loadMore(firstPage = false) {

    let currentPage = page
    if (firstPage){
      currentPage = 1
    }

    // 从后台获取流水
    const res = await queryIncomeLog({
      current: currentPage, pageSize: 10
    });
    if (res.status === "done"){
      if (currentPage === 1){

        // 重载数据
        const emptyList = [...data]
        emptyList.splice(0, emptyList.length)
        res.data?.map((item)=>(
          emptyList.push(item)
        ))
        setData(emptyList)
      }else {

        // 插入数据
        const newData = [...data];
        res.data?.map((item)=>(
          newData.push(item)
        ))
        setData(newData)
      }

      // 计算是否有下一页
      setHasMore(res.total > 10 * currentPage)

      // 下一页
      setPage(currentPage + 1)
    }
  }

  // 更新数据
  const [needUpdate, setNeedUpdate] = useState(false)
  useEffect(()=>{
    loadMore(true)
  }, [props, needUpdate])

  // 自定义下拉获取
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const InfiniteScrollContent = ({ hasMore }: { hasMore?: boolean }) => {
    return (
      <>
        {hasMore ? (
          <>
            <span>Loading</span>
            <DotLoading />
          </>
        ) : (
          <span>--- 我是有底线的 ---</span>
        )}
      </>
    )
  }

  // 滑动操作
  const rightActions: any[] = [
    {
      key: 'edit',
      text: '修改',
      color: '#1890ff',
      onClick: ()=>{
        handleUpdateModalVisible(true)
      }
    },
    {
      key: 'delete',
      text: '删除',
      color: 'danger',
      onClick: ()=>{
        Dialog.show({
          content: "真的要删除？",
          closeOnAction: true,
          actions: [
            [
              {
                key: 'cancel',
                text: '取消',
              },
              {
                key: 'delete',
                text: '删除',
                bold: true,
                danger: true,
                onClick: async ()=>{
                  // 执行删除操作
                  const success = await handleSingleRemove(currentRow);
                  if (success) {
                    // 删除成功，从data中删除此行数据
                    const newData = [...data]
                    // eslint-disable-next-line array-callback-return
                    newData.map((item)=>{
                      if (item.id === currentRow?.id){
                        // 删除
                        newData.splice(newData.indexOf(item), 1)
                        setData(newData)
                      }
                    })
                  }
                }
              },
            ],
          ]
        })
      }
    },
  ]
  return (
    <>
    <List
      style={{
        position: "relative",
        width: `calc(100vw - 20px)`,
        marginLeft: -10,
        "--font-size": "15px"
      }}
    >
      {data.map((item) => {
        if (item.date) {
          // 有日期的，插入一个日期列
          return (
            <>
              <List.Item key={"item_" + item.id} className={Style.itemBackground}>
                <div className={Style.inlineBlock}>
                  <b className={Style.days}>{dayjs(item.date).format("DD ")}</b>
                </div>
                <div className={Style.monthAndYear}>
                  {dayjs(item.date).format("/ MM / YYYY")}
                </div>
              </List.Item>
              <SwipeAction
                key={item.id}
                rightActions={rightActions}
                onActionsReveal={() => {
                  setCurrentRow(item)
                }}
              >
                <List.Item
                  key={"item" + item.id}
                  prefix={<Avatar src={"/static/icons/" + item.incomeType?.icon}/>}
                  description={<span>{dayjs(item.time).format("HH:mm")}</span>}
                  extra={
                    <>
                      <a
                        className={Style.itemContent}
                      >
                        <span style={{paddingTop: 5}}>{item.remark}</span>
                      </a>
                      <a
                        onClick={()=>{Toast.show({content: "这是收入金额。"})}}
                        className={Style.inMoney}
                      >
                        ¥ {item.money}
                      </a>
                    </>
                  }
                >
                  {item.incomeType?.name}
                </List.Item>
              </SwipeAction>
            </>
          )
        }else{

          // 同一天的不同时间的，只返回时间的
          return (
            <SwipeAction
              key={item.id}
              rightActions={rightActions}
              onActionsReveal={() => {
                setCurrentRow(item)
              }}
            >
              <List.Item
                key={item.id}
                prefix={<Avatar src={"/static/icons/" + item.incomeType?.icon}/>}
                description={<span>{dayjs(item.time).format("HH:mm")}</span>}
                extra={
                  <>
                    <a className={Style.itemContent}>
                      <span style={{paddingTop: 5}}>{item.remark}</span>
                    </a>

                    <a
                      onClick={()=>{Toast.show({content: "这是收入金额。"})}}
                      className={Style.inMoney}
                    >
                      ¥ {item.money}
                    </a>
                  </>
                }
              >
                {item.incomeType?.name}
              </List.Item>
            </SwipeAction>
          )
        }
      })}
    </List>
    <InfiniteScroll
      loadMore={loadMore}
      hasMore={hasMore}
      threshold={0}
    >
      <InfiniteScrollContent hasMore={hasMore} />
    </InfiniteScroll>
    <div style={{height: 100, width: `100%`, position: "relative"}}/>

      <UpdateForm
        onCancel={()=>{
          handleUpdateModalVisible(false)
          setCurrentRow(undefined)
          // 更新数据
          setNeedUpdate(!needUpdate)
        }}
        onSubmit={async (value)=>{
          const success = await handleUpdate(value, currentRow);
          if (success){
            handleUpdateModalVisible(false)
            setCurrentRow(undefined)

            // 更新数据
            setNeedUpdate(!needUpdate)
          }
        }}
        modalVisible={updateModalVisible}
        values={currentRow || {}}
      />
    </>
  )
}
export default IncomeLogs;
